﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using webnew.Common;

namespace webnew.Systems
{
    public partial class S_userEdit : WebPageBase.EditBase
    {
        private List<Model.Sys_NavigationInfo> NavList = null;  //所有导航列表
        private System.Data.DataTable dt = null;   //一个或多个角色的导航ID列表
        protected void Page_Load(object sender, EventArgs e)
        {
           
            _ListSrc = "S_userList.aspx";
            _ListQueryString = "UserType,CompId,DeptId,TrueName,TitleName,Status,RecordCount,CurrentPageIndex";
            txtTrueName.Text = hfStaffName.Value == "" ? txtTrueName.Text : hfStaffName.Value;
            if (_RecordId == null) btnViewNav.Visible = true;
            
            if (!IsPostBack)
            {
                SetTitle(true, "后台管理 >> 用户管理");
                webnew.Common.CommonHelper.DataDdlBind(ddlUserType, new BLL.Sys_UserType().GetList(), "UserTypeName", "id");               
                UcRoleCheckBox1.ShowCheckBox();
                
                
            }
        }

        #region Pagemethods
        /// <summary>
        /// 验证用户名,用户名是否存在
        /// </summary>
        [WebMethod]
        public static bool ValidLoginID(string loginID)
        {

            if (new BLL.Sys_User().ExistLoginId(loginID) =="1")
            {
                return true;
            }
            else
            {
                return false;
            }
        }

       
        #endregion
        



        /// <summary>
        /// 重写基类显示数据方法
        /// </summary>
        protected override void ShowData()
        {
            //base.ShowData();
            Model.Sys_UserInfo model = new BLL.Sys_User().GetModel(_RecordId);
            ddlUserType.SelectedValue = model.UserTypeId;
            hfStaffId.Value = model.StaffId;
            txtLoginID.Text = model.Loginid;        
            //txtLoginID.Enabled = !(model.Loginid.Length > 0);

            txtTrueName.Text = new BLL.Sys_Staff().GetModel(model.StaffId).TrueName;
            hfStaffName.Value = model.truename;
            txtRemark.Text = model.remark;
            UcRoleCheckBox1.ShowCheckBox(model.Id);
            //显示用户权限树
            NavList = new BLL.Sys_Navigation().GetList();  //获取存在的所有导航和按钮列表
            dt = new BLL.Sys_RoleNavigation().GetUserNavigation(_RecordId); //根据用户ID获取所有导航和按钮Id列表
            CreateTree();
            ViewState["LoginID"] = model.Loginid; 
           
        }

        //查看当前用户所选的角色权限
        protected void btnViewNav_Click(object sender, EventArgs e)
        {
            //显示用户权限树
            NavList = new BLL.Sys_Navigation().GetList();  //获取存在的所有导航和按钮列表
            List<Model.Sys_UserRoleInfo> lstRole = UcRoleCheckBox1.GetAllCheckedValue("");
            if (lstRole.Count > 0)
            {
                dt = new BLL.Sys_RoleNavigation().GetRoleListNavigation(lstRole); //根据用户ID获取所有导航和按钮Id列表
                TreeView1.Nodes.Clear();
                CreateTree();
                TreeView1.ExpandAll();
            }
            else TreeView1.Nodes.Clear();
        }


        #region  根据导航ID列表生成权限树控件
        private void CreateTree()
        {
            foreach (Model.Sys_NavigationInfo model in NavList.Where(p => p.ParentID == Guid.Empty.ToString()))
            {

                TreeNode ParentNode = new TreeNode(model.NaviName, model.Id.ToString(), "/App_Themes/Images/Icon/" + model.picsrc + ".gif");
                ParentNode.ShowCheckBox = true;
                ParentNode.SelectAction = TreeNodeSelectAction.Expand;
                foreach (System.Data.DataRow dr in dt.Rows)
                {
                    if (ParentNode.Value == dr["NavigationID"].ToString())
                    {
                        ParentNode.Checked = true;
                    }
                }
                TreeView1.Nodes.Add(ParentNode);
                GetChildNodes(ParentNode);
            }
        }

        private void GetChildNodes(TreeNode ParentNode)
        {
            foreach (Model.Sys_NavigationInfo model in NavList.Where(p => p.ParentID == ParentNode.Value))
            {
                TreeNode ChildNode = new TreeNode(model.NaviName, model.Id.ToString(), "~/App_Themes/Images/Icon/" + model.picsrc + ".gif");
                ChildNode.ShowCheckBox = true;
                ChildNode.SelectAction = TreeNodeSelectAction.Expand;
                foreach (System.Data.DataRow dr in dt.Rows)
                {
                    if (ChildNode.Value == dr["NavigationID"].ToString())
                    {
                        ChildNode.Checked = true;
                    }
                }
                if (NavList.Exists(p => p.ParentID == model.Id)) GetChildNodes(ChildNode);
                ParentNode.ChildNodes.Add(ChildNode);
            }
        }
        #endregion

        /// <summary>
        /// 重写基类验证数据方法
        /// </summary>
        protected override List<PageValid> _SetValidData()
        {

            List<PageValid> lst = new List<PageValid>();
            if (!(_RecordId != null)) //添加状态
            {
                lst.Add(new PageValid("用户名", txtLoginID.Text, PageValid.validType.CommonValid, false, 30));
                lst.Add(new PageValid("密码", txtPassword.Text, PageValid.validType.CommonValid, false, 30));
            }
            lst.Add(new PageValid("真实姓名", txtTrueName.Text, PageValid.validType.CommonValid, false, 30));
            lst.Add(new PageValid("备注", txtRemark.Text, PageValid.validType.CommonValid, true, 100));
           
            if (_RecordId != null)
            {
                if (ViewState["LoginID"].ToString() != txtLoginID.Text.ToString())
                {
                    lst.Add(new PageValid("用户名", "1", new BLL.Sys_User().ExistLoginId(txtLoginID.Text).ToString(), PageValid.validType.NoSameValid, "已存在，请重新输入"));
                }
            }
            else
            {
                lst.Add(new PageValid("用户名", "1", new BLL.Sys_User().ExistLoginId(txtLoginID.Text).ToString(), PageValid.validType.NoSameValid, "已存在，请重新输入"));
            }
           
            return lst;
        }

        /// <summary>
        /// 重写基类保存数据方法
        /// </summary>
        /// <returns></returns>
        protected override int SaveData()
        {
            Model.Sys_UserInfo model = new Model.Sys_UserInfo();
            model.Id = _RecordId;
            if (ddlUserType.SelectedItem.Text == "公司用户")
            {
                model.StaffId = hfStaffId.Value == "" ? Guid.Empty.ToString() : hfStaffId.Value;
            }
            else if (ddlUserType.SelectedItem.Text == "油库用户") model.StaffId = hfStaffId.Value == "" ? Guid.Empty.ToString() : hfStaffId.Value;
            else model.StaffId = Guid.Empty.ToString();

            model.UserTypeId = ddlUserType.SelectedValue;
            model.Loginid = txtLoginID.Text;
            model.password = (txtPassword.Text == string.Empty) ? "" : Common.CommonHelper.MyMd5(txtPassword.Text);
            model.truename = txtTrueName.Text;
            model.remark = txtRemark.Text;
            model.isdel = MyConvert.toInt32(dllStatus.SelectedValue);
            List<Model.Sys_UserRoleInfo> lstRole = UcRoleCheckBox1.GetAllCheckedValue(model.Id);
            
            //----------系统日志model

            Model.Sys_LogInfo modelLog = new webnew.Model.Sys_LogInfo();
            modelLog.UserID = UserInfor.Id;                  //用户ID
            modelLog.IP = new BLL.Sys_Log().GetUserIP(System.Web.HttpContext.Current.Request);  //IP
            modelLog.Module = new BLL.Sys_Navigation().GetModuleName(this.GetType().BaseType.Name);   //模块名
            modelLog.CreateDate = DateTime.Now;           //创建时间

            string error = "";                   //获取错误信息

            if (_RecordId != null)//修改狀態
            {
                //if (txtLoginID.Enabled == true)
                //{
                //    if (new BLL.Sys_User().GetCount("Sys_User", " LoginID='" + model.Loginid + "'") > 0)
                //    {
                //        Jscript.Alert(this, "系统已经存在该用户名");
                //        txtLoginID.Focus();
                //        return 0;
                //    }
                //}
                //else
                //{
                    try
                    {
                        return new BLL.Sys_User().Modify(model, lstRole);
                    }
                    catch (Exception e)
                    {
                        error = e.ToString();
                    }
                    finally
                    {
                        //添加一条系统日志
                        new BLL.Sys_Log().AddSysLog(error, "修改", modelLog, "系统用户", "用户，用户名为" + txtLoginID.Text);
                    }
                //}
            }
            else  //添加狀態
            {
                ////判断系统是否已经存在用户登入ID号
                //if (new BLL.Sys_User().GetCount("Sys_User", " LoginID='" + model.Loginid + "'") > 0)
                //{
                //    Jscript.Alert(this, "系统已经存在该用户名");
                //    txtLoginID.Focus();
                //    return 0;
                //}
                //else
                //{
                   
                    try
                    {
                        model.Id = Guid.NewGuid().ToString();
                       
                        new BLL.Sys_User().Add(model, lstRole);
                        
                    }
                    catch (Exception e)
                    {
                        error = e.ToString();
                    }
                    finally
                    {
                        //添加一条系统日志
                        new BLL.Sys_Log().AddSysLog(error, "添加", modelLog, "系统用户", "用户，用户名为" + txtLoginID.Text);
                    }
               // }
            }

            //弹出文本框成功或者失败
            if (error == "") { return 1; }       //成功
            else { return 0; }                   //失败
          
        }

        protected void btnUpDatePwd_Click(object sender, EventArgs e)
        {
            if(new BLL.Sys_User().UpdateMd5Pwd()=="1") ShowMsg="更改成功";
            else  ShowMsg="更改失败";
        }

    }
}
